<?php

class GaAPI_Services_AdGroupAd extends GaAPI_Services_Abstract {

    protected $_serviceName = 'AdGroupAdService';

    protected function call($name, $params = false) {
        if ($this->getApi()->checkParam('client_email')) {
            return parent::call($name, $params);
        }
        return $this->throwError("AdGroups methods require clients_email to be set");
    }

    /**
     * @return GaAPI_Objects_AdGroup_Ad_Page
     */
    public function getAll() {
        $selector = $this->newSelector();
        return $this->get($selector);
    }

    public function addNew(GaAPI_Objects_AdGroup_Ad $adGroupAd) {
        $operation = $this->newOperation();
        $operation->operator = 'ADD';
        $operation->operand = $adGroupAd;

        $return = $this->mutate($operation);
        return $this->newAd()->setFromArray($return);
    }

    public function update(GaAPI_Objects_AdGroup_Ad $adGroupAd) {
        $operation = $this->newOperation();
        $operation->operator = 'SET';
        $operation->operand = $adGroupAd;

        $return = $this->mutate($operation);
        return $this->newAd()->setFromArray($return);
    }

    /**
     *
     * @param GaAPI_Objects_AdGroup_Selector $selector
     * @return GaAPI_Objects AdGroup_Page
     */
    public function get(GaAPI_Objects_AdGroup_Ad_Selector $selector) {
        $result = $this->call('get',(string) $selector);
        
        $page = $this->newPage();
        $page->setApi($this->getApi());
        $page->setFromArray($result['rval']);

        return $page;
    }

    /**
     * @return GaAPI_Objects_AdGroup_Ad_Operation
     */
     public function newOperation() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_AdGroup_Ad_Operation');
        $operation = new GaAPI_Objects_AdGroup_Ad_Operation();
        return $operation;
    }

    /**
     * @return GaAPI_Objects_AdGroup_Ad_Selector
     */
     public function newSelector() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_AdGroup_Ad_Selector');
        $selector = new GaAPI_Objects_AdGroup_Ad_Selector();
        $selector->setApi($this->getApi());
        return $selector;
    }

    /**
     * @return GaAPI_Objects_AdGroup_Ad_Page
     */
     public function newPage() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_AdGroup_Ad_Page');
        $page = new GaAPI_Objects_AdGroup_Ad_Page();
        return $page;
    }

    /**
     * @return GaAPI_Objects_AdGroup_Page
     */
     public function newAd() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_AdGroup_Ad');
        $page = new GaAPI_Objects_AdGroup_Ad();
        return $page;
    }

}